﻿using BW.Mes.WinForms.Process.OperationModel.ApiResult;
using BW.Mes.WinForms.Process.OperationModel.Model;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BW.Mes.WinForms.Process.OperationModel
{
    public partial class AddOperationForm : DevExpress.XtraEditors.XtraForm
    {
        private HttpClient httpClient;
        
        // 添加操作人员列表和字典用于存储数据
        private List<UserModel> users = new List<UserModel>();
        private Dictionary<string, string> userNameToId = new Dictionary<string, string>();
        
        // 添加部门和车间字典用于存储数据
        private List<DepartmentModel> departments = new List<DepartmentModel>();
        private Dictionary<string, long> departmentNameToId = new Dictionary<string, long>();
        private List<WorkshopModel> workshops = new List<WorkshopModel>();
        private Dictionary<string, long> workshopNameToId = new Dictionary<string, long>();
        
        // 声明事件委托，用于通知父窗体刷新数据
        public delegate void OperationAddedEventHandler(object sender, EventArgs e);
        public event OperationAddedEventHandler OperationAdded;

        // 添加触发事件的方法
        protected virtual void OnOperationAdded()
        {
            OperationAdded?.Invoke(this, EventArgs.Empty);
        }

        public AddOperationForm()
        {
            InitializeComponent();
            InitializeHttpClient();
            
            // 注册窗体加载事件
            this.Load += AddOperationForm_Load;
        }

        private void InitializeHttpClient()
        {
            // Ignore SSL certificate validation for localhost development
            var handler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true
            };
            httpClient = new HttpClient(handler);
            httpClient.Timeout = TimeSpan.FromSeconds(30);
            
            // 不再设置BaseAddress，改为在每次请求时使用完整URL
        }

        /// <summary>
        /// 窗体加载事件
        /// </summary>
        private async void AddOperationForm_Load(object sender, EventArgs e)
        {
            try
            {
                // 并行加载各种数据以提高性能
                var loadTasks = new List<Task>
                {
                    LoadOperationManagers(),
                    LoadDepartments(),
                    LoadWorkshops()
                };
                
                // 等待所有加载任务完成
                await Task.WhenAll(loadTasks);
                
                // 设置默认值
                if (OperationStates.Properties.Items.Count == 0)
                {
                    // 修复：使用RadioGroupItem数组代替object数组
                    OperationStates.Properties.Items.AddRange(new RadioGroupItem[] { 
                        new RadioGroupItem(true, "启用"), 
                        new RadioGroupItem(false, "禁用") 
                    });
                    OperationStates.SelectedIndex = 0; // 默认选择启用
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载初始数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 从API获取操作人员数据并填充下拉框
        /// </summary>
        private async Task LoadOperationManagers()
        {
            try
            {
                // 使用完整URL，不再设置BaseAddress
                var response = await httpClient.GetAsync("http://120.26.197.100:8022/T1/Auth");
                
                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsStringAsync();
                    var result = JsonConvert.DeserializeObject<AddResult<List<UserModel>>>(content);
                    
                    if (result != null && result.data != null)
                    {
                        users = result.data;
                        
                        // 清空现有项
                        OperationHead.Properties.Items.Clear();
                        userNameToId.Clear();
                        
                        // 填充下拉框和字典
                        foreach (var user in users)
                        {
                            OperationHead.Properties.Items.Add(user.name);
                            userNameToId[user.name] = user.id;
                        }
                    }
                }
                else
                {
                    XtraMessageBox.Show("获取操作人员数据失败：" + response.ReasonPhrase);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("获取操作人员数据出错：" + ex.Message);
            }
        }
        
        /// <summary>
        /// 从API获取部门数据并填充下拉框
        /// </summary>
        private async Task LoadDepartments()
        {
            try
            {
                using (var client = new HttpClient())
                {
                    // 忽略SSL证书验证
                    var handler = new HttpClientHandler
                    {
                        ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true
                    };
                    using (var secureClient = new HttpClient(handler))
                    {
                        var response = await secureClient.GetAsync("http://120.26.197.100:8022/T5/Department/GetAll");
                        
                        if (response.IsSuccessStatusCode)
                        {
                            var content = await response.Content.ReadAsStringAsync();
                            var result = JsonConvert.DeserializeObject<AddResult<List<DepartmentModel>>>(content);
                            
                            if (result != null && result.data != null)
                            {
                                departments = result.data;
                                
                                // 填充部门下拉框和字典
                                if (OperationDepartment != null && OperationDepartment.Properties != null)
                                {
                                    OperationDepartment.Properties.Items.Clear();
                                    departmentNameToId.Clear();
                                    
                                    foreach (var dept in departments)
                                    {
                                        OperationDepartment.Properties.Items.Add(dept.Name);
                                        departmentNameToId[dept.Name] = dept.Id;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载部门数据失败: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 从API获取车间数据并填充下拉框
        /// </summary>
        private async Task LoadWorkshops()
        {
            try
            {
                using (var client = new HttpClient())
                {
                    // 忽略SSL证书验证
                    var handler = new HttpClientHandler
                    {
                        ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true
                    };
                    using (var secureClient = new HttpClient(handler))
                    {
                        var response = await secureClient.GetAsync("http://120.26.197.100:8022/T2/Workshop/ShowWorkshop");
                        
                        if (response.IsSuccessStatusCode)
                        {
                            var content = await response.Content.ReadAsStringAsync();
                            var result = JsonConvert.DeserializeObject<AddResult<List<WorkshopModel>>>(content);
                            
                            if (result != null && result.data != null)
                            {
                                workshops = result.data;
                                
                                // 填充车间下拉框和字典
                                if (OperationWorkshop != null && OperationWorkshop.Properties != null)
                                {
                                    OperationWorkshop.Properties.Items.Clear();
                                    workshopNameToId.Clear();
                                    
                                    foreach (var workshop in workshops)
                                    {
                                        OperationWorkshop.Properties.Items.Add(workshop.workshopName);
                                        workshopNameToId[workshop.workshopName] = workshop.Id;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载车间数据失败: {ex.Message}");
            }
        }

        private void labelControl1_Click(object sender, EventArgs e)
        {

        }
        
    
        
        
      

        private async void simpleButton1_Click_1(object sender, EventArgs e)
        {
            try
            {
                // 验证必填字段
                if (string.IsNullOrWhiteSpace(OperationCode.Text))
                {
                    XtraMessageBox.Show("请输入工艺编码！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    OperationCode.Focus();
                    return;
                }

                if (string.IsNullOrWhiteSpace(OperationName.Text))
                {
                    XtraMessageBox.Show("请输入工艺名称！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    OperationName.Focus();
                    return;
                }
                
                // 获取选中的操作人员ID
                string operationHeadId = string.Empty;

                // 通过选中索引获取ID
                if (OperationHead.SelectedIndex >= 0 && OperationHead.SelectedIndex < users.Count)
                {
                    operationHeadId = users[OperationHead.SelectedIndex].id;
                }
                // 如果索引方法失败，再尝试通过文本匹配
                else if (!string.IsNullOrEmpty(OperationHead.Text) && userNameToId.ContainsKey(OperationHead.Text))
                {
                    operationHeadId = userNameToId[OperationHead.Text];
                }
                
                // 获取部门ID
                long departmentId = 0;
                if (OperationDepartment != null && !string.IsNullOrEmpty(OperationDepartment.Text) && 
                    departmentNameToId.ContainsKey(OperationDepartment.Text))
                {
                    departmentId = departmentNameToId[OperationDepartment.Text];
                }
                
                // 获取车间ID
                long workshopId = 0;
                if (OperationWorkshop != null && !string.IsNullOrEmpty(OperationWorkshop.Text) && 
                    workshopNameToId.ContainsKey(OperationWorkshop.Text))
                {
                    workshopId = workshopNameToId[OperationWorkshop.Text];
                }

                // 获取RadioGroup选中的值（启用/禁用）
                bool operationState = false;
                if (OperationStates.SelectedIndex >= 0 && OperationStates.EditValue != null)
                {
                    // 尝试直接获取布尔值
                    if (OperationStates.EditValue is bool)
                    {
                        operationState = (bool)OperationStates.EditValue;
                    }
                    // 如果无法直接获取，根据索引判断（0="启用"，1="禁用"）
                    else
                    {
                        operationState = (OperationStates.SelectedIndex == 0);
                    }
                }

                // 创建操作数据对象
                var operationData = new OperationModel2()
                {
                    operationCode = OperationCode.Text,
                    operationName = OperationName.Text,
                    operationHead = operationHeadId, // 使用ID而不是文本
                    operationDepartment = departmentId,
                    operationWorkshop = workshopId,
                    operationState = operationState, // 使用从控件获取的值
                    operationDesc = OperationDesc.Text,
                    operationMaterials = OperationMaterials.Text,
                };

                // 先创建handler
                var handler = new HttpClientHandler
                {
                    ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true
                };

                // 然后在using语句中使用这个handler
                using (var client = new HttpClient(handler))
                {
                    // 设置请求地址
                    var baseUrl = "http://localhost:5179";
                    var apiUrl = $"{baseUrl}/api/OperationModel/AddOperationModel";

                    // 创建JSON数据
                    var json = JsonConvert.SerializeObject(operationData);
                    Console.WriteLine($"发送数据: {json}");

                    // 创建请求内容(指定编码为UTF-8，内容类型为application/json)
                    var content = new StringContent(json, Encoding.UTF8, "application/json");

                    // 发送POST请求
                    var response = await client.PostAsync(apiUrl, content);

                    // 判断是否成功
                    if (response.IsSuccessStatusCode)
                    {
                        var responseContent = await response.Content.ReadAsStringAsync();
                        Console.WriteLine($"API响应: {responseContent}");
                        
                        XtraMessageBox.Show("添加成功！");

                        // 触发事件通知父窗体刷新数据
                        OnOperationAdded();

                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                    else
                    {
                        var errorContent = await response.Content.ReadAsStringAsync();
                        XtraMessageBox.Show($"添加失败：{response.ReasonPhrase}\n{errorContent}");
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("保存数据出错：" + ex.Message);
            }
        }
    }
}